import './subtitle.css';
import i18next from '../../utils/i18next/i18n';
class SubTitle {
	constructor(onAiStartSpeak, onAiStartDone, onMembersLeave, container = '', options = {}) {
		this.subtitles = [];
		this.onAiStartSpeak = onAiStartSpeak;
		this.onAiStartDone = onAiStartDone;
		this.onMembersLeave = onMembersLeave;
		this.container = container || document.body;
		this.width = null;
		this.height = null;
		this.containerId = null;
		this.left = 0;
		this.bottom = 50;
		this.className = null;
		this.zIndex = 10;
		this.options = options;
		this.ulContainer = null;
		this.msgId = null;
		this.scrollTimer = null;
		this.user = null;
		this.init();
	}

	init() {
		this.initContainer();
		this.createView();
		this.initEvent();
		console.log('###字幕文件加载成功###');
	}

	/** 初始化事件 */
	initEvent() {
		this.onAiStartSpeak((status, resp, msgId) => {
			console.log('onAiStartSpeak', status, resp, msgId);
		});
		this.onAiStartDone((status, resp, msgId) => {
			this.clearTimer();
			console.log('onAiStartDone', status, resp, msgId);
		});
		this.onMembersLeave(info => {
			const { id = null } = info.data;
			const subtitle = this.subtitles.find(item => item.from === id);
			if (subtitle) {
				let childrenNode = document.getElementById(`li-${subtitle.id}`);
				childrenNode && this.ulContainer.removeChild(childrenNode);
			}
			console.log('onMembersLeave', info, this.subtitles, subtitle);
		});
	}

	/** 初始化容器 */
	initContainer() {
		const {
			width = 'auto',
			height = 300,
			warpper = document.body,
			className = 'widget-subtitle-warpper',
			id = 'widget-subtitle-warpper',
			left = 0,
			bottom = 80,
			zIndex = 10,
			user = null
		} = this.options;
		this.width = width;
		this.height = height;
		this.container = warpper;
		this.className = className;
		this.containerId = id;
		this.left = left;
		this.bottom = bottom;
		this.zIndex = zIndex;
		this.user = user;
	}

	/** 创建视图层 */
	createView() {
		this.ulContainer = document.createElement('ul');
		this.ulContainer.id = this.containerId;
		this.ulContainer.style.zIndex = this.zIndex;
		this.ulContainer.style.width = this.width + 'px';
		this.ulContainer.style.maxHeight = this.height + 'px';
		this.ulContainer.style.bottom = this.bottom + 'px';
		this.ulContainer.style.left = this.left + 'px';
		this.ulContainer.style.zIndex;
		this.ulContainer.className = this.className;
		this.container.appendChild(this.ulContainer);
	}

	/** 创建子元素 */
	createChild(text) {
		const childContianer = document.createElement('li');
		const nameLabel = document.createElement('span');
		const textContianer = document.createElement('span');
		nameLabel.className = this.user && this.user.clientId === text.from ? 'self-label' : 'other-label';
		textContianer.className = this.user && this.user.clientId === text.from ? 'self-subtitle-text subtitle-text' : 'other-subtitle-text subtitle-text';
		childContianer.className = 'subtitle-text-warpper';
		nameLabel.innerText = this.getRoleLabel(text);
		childContianer.appendChild(nameLabel);
		childContianer.appendChild(textContianer);
		childContianer.id = `li-${text.id}`;
		textContianer.innerHTML = this.filterText(text.data);
		textContianer.id = text.id;
		this.ulContainer.appendChild(childContianer);
		textContianer.scrollIntoView(false);
		this.addTextTimer();
	}

	setSubtitle(data) {
		this.subtitles = [...this.subtitles, data];
		this.msgId = data.id;
		this.createChild(data);
	}

	getSubTitle() {
		return this.subtitles;
	}

	clear() {
		this.subtitles = [];
	}

	hide() {
		if (this.ulContainer) {
			this.ulContainer.style.display = 'none';
		}
	}

	show() {
		if (this.ulContainer) {
			this.ulContainer.style.display = 'block';
		}
	}

	isAgent(role) {
		return role === 'agent';
	}

	/** 忽略文字 */
	filterText(text) {
		// FIX BUG : Uncaught TypeError: text.indexOf is not a function
		if (!text) return '';
		if (typeof text !== 'string') {
			return JSON.stringify(text);
		}
		if (text === 'silence-msg' || text === 'OnTaskFailed' || text.indexOf('Timeout to') !== -1) {
			return '';
		} else {
			return text;
		}
	}

	getRoleLabel(text) {
		const mine = i18next.t('mine');
		const agent = i18next.t('agent');
		return this.user.clientId === text.from ? `${mine}：` : this.isAgent(text.fromUser.role) ? `${agent} ${text.fromUser.name}：` : `${text.fromUser.name}：`;
	}

	addTextTimer() {
		// 字幕行数 7， 字幕一行个数 20， ai 每秒播报字幕个数 4
		const startScrolltimer = ((7 * 20) / 4 / 2) * 1000;
		setTimeout(() => {
			const ele = document.getElementById(this.msgId);
			if (ele) {
				this.scrollTimer = setInterval(() => {
					if (ele.scrollHeight - ele.scrollTop <= ele.offsetHeight - 16) {
						clearInterval(this.scrollTimer);
						console.log('clear interval:', this.scrollTimer);
						this.scrollTimer = null;
					}
					ele.scrollTop++;
				}, 6000 / 20);
			}
		}, startScrolltimer);
	}

	clearTimer() {
		if (this.scrollTimer) {
			clearInterval(this.scrollTimer);
			this.scrollTimer = null;
		}
	}

	pxToNumber(px) {
		const num = Number(px.replace('px', ''));
		return num;
	}

	/** 移除字幕 */
	remove() {
		this.clearTimer();
		this.subtitles = [];
		this.removeChild();
	}

	/** 移除子元素 */
	removeChild() {
		if (this.ulContainer.childNodes.length > 0) {
			for (let i = 0; i < this.ulContainer.childNodes.length; i++) {
				if (this.ulContainer.childNodes[i]) {
					this.ulContainer.replaceChild(this.ulContainer.childNodes[i]);
				}
			}
		}
	}

	/** 销毁元素 */
	destory() {
		if (this.container) {
			this.ulContainer && this.container.removeChild(this.ulContainer);
		} else {
			this.ulContainer && document.body.removeChild(this.ulContainer);
		}
		this.clearTimer();
		this.subtitles = [];
		this.onAiStartSpeak = null;
		this.onAiStartDone = null;
		this.container = null;
		this.width = null;
		this.height = null;
		this.containerId = null;
		this.left = 0;
		this.bottom = 50;
		this.className = null;
		this.zIndex = 10;
		this.options = null;
		this.ulContainer = null;
		this.msgId = null;
	}
}

export default SubTitle;
